// 页面左边导航栏状态管理
import { ref } from 'vue'
import { defineStore } from 'pinia'
import { useOverlayStore } from '@/Stores/overlay';
import request from '@/Utils/request';

interface TreeItemDataType {
    resUrl: string;
    resCode: string;
    resIcon: string;
};

interface TreeItemType {
    id: string;
    name: string;
    parentId: string;
    type: string;
    data: TreeItemDataType;
    checked: boolean;
    children: TreeItemType[];
    title: string;
    label: string;
    value: string;
};

/**
 * @author Elliot
 * @date 2023-04-18 17:53
 * @description 左边导航栏数据管理
 */
export const useMenuStore = defineStore('menu', () => {

    const isShow = ref<string | boolean>(''); // 是否显示弹窗

    const menuList = ref<TreeItemType[]>([]);

    const getMenuStatus = ref<'waiting' | 'ing' | 'fail' | 'success'>('waiting');
    
    function triggerMenu () {
        const overlay = useOverlayStore();
        isShow.value = !isShow.value;
        overlay.setShow(!overlay.isShow);
    };

    function setShow (show = false) {
        isShow.value = show;
    };

    const getList = () => {
        return request({
            url: '/user/auth/adminGetPersonalMenuTree',
            query: {
                platformCode: 'ENTERPRISE'
            },
            method: 'post'
        });
    }

    const replaceUrl = {
        '/core/user/shop/list.html': '/shopList',
        '/core/schedul/schedule.html': '/shopSchedul',
        '/core/schedul/knowledge.html': '/knowledge',
        '/core/auth/enterpriseInfo.html': '/enterpriseInfo',
        '/core/workOrder/workOrderIndex.html': '/workOrder',
        '/core/auth/memberList.html': '/memberList', // 成员管理
        '/core/workOrder/workOrderAnalysis.html': '/workOrderAnalysis', // 工单分析
        '/core/user/role/rolelist.html': '/roleListPermission', // 角色权限
        '/core/user/usergroup/userGroup.html': '/userGroupList',
        // '/core/workOrder/recycleList.html': '/wrokOrderRecycleList',
        '/core/qcs/chat/standard/list.html': '/qualityStandardList', // 标准设置列表
        '/core/qcs/chat/label/list.html': '/qualityTagList', // 质检系统-标签管理
        '/core/dms/shopIndicator.html': '/shopIndicatorList',
        '/core/dms/reportForms/index.html': '/reportMangement',
        '/core/dms/indexManage/index.html': '/indicatorStandard',
        '/core/qcs/chat/record/recordIndex.html': '/checkWorkbench',
        '/core/qcs/chat/analyse/index.html': '/checkAnalysis',
        '/core/qcs/evaluate/evaluateList.html': '/evaluateList',
        '/core/qcs/evaluate/label/list.html': '/evaluateLabelList', // 评价标签库
        '/core/qcs/evaluate/evaluateAnalysis.html': '/evaluateAnalysis',
        '/core/lms/train/material/index.html': '/material', // 素材中心
        '/core/lms/train/certification/index.html': '/certificationCenter', // 认证中心
        '/core/lms/personal_manage/index.html': '/personalCertification', // 个人认证
        '/core/lms/train/certificationAnalysis/certificationAnalysis.html': '/certificationAnalysis', // 认证分析
        '/core/qcs/chat/check/index.html': '/checkRecords', // 质检记录
        '/core/qcs/chat/record/recordAssignmentIndex.html': '/checkAssignment', // 质检工作管理
        '/core/lms/deill_resource/index.html': '/trainSource', // 训练库源
        '/core/lms/deill_person/index.html': '/userTrain', // 个人训练库
        '/core/lms/deill_manage/index.html': '/trainManagement', // 训练库管理
        '/core/lms/deill_analysis/index.html': '/analysisTrainResult', // 训练结果分析
        '/core/dms/biAnalysis.html': '/biAnalysis', // BI分析
        '/core/workOrder/statisticalChart.html': '/workOrderStatistics', // 工单统计
    };
    
    type keysType = keyof(typeof replaceUrl);

    async function getMenuList (count = 0) : Promise<TreeItemType[]> {
        if (['waiting', 'fail'].includes(getMenuStatus.value)) {
            getMenuStatus.value = 'ing';
            try {
                // tree = await getList() as TreeItemType[];
                const tree = await getList();
                if (tree.length > 0) {
                    getMenuStatus.value = 'success';
                } else {
                    getMenuStatus.value = 'waiting';
                }
                setTreeData(handleTree(tree));
                // setTreeData(tree);
                // console.log('tree: ', tree);
                return tree;
            } catch (error) {
                getMenuStatus.value = 'fail';
                return [];
            }
        } else if (getMenuStatus.value === 'ing' || count <= 10) {
            await new Promise(resolve => setTimeout(resolve, 10));
            return await getMenuList(count + 1);
        } else {
            return menuList.value;
        }
    }

    // 处理导航数据
    const handleTree = (tree: TreeItemType[]) : TreeItemType[] => {
        for (let i = 0; i < tree.length; i++) {
            // console.log(tree[i].data.resIcon)
            if (tree[i].data.resIcon) {
                tree[i].data.resIcon = {
                    'dianpuguanli-01': '<svg class="iconpark-icon icon-20"><use href="#application-9koknedj"></use></svg>', // 店铺管理
                    'quanxianlan-01': '<svg class="iconpark-icon icon-20"><use href="#internal-data-9kokjm4c"></use></svg>', // 数据系统
                    'peiguxitong-01': '<svg class="iconpark-icon icon-20"><use href="#file-protection-one"></use></svg>', // 培估系统
                    'zhijianguanli-01': '<svg class="iconpark-icon icon-20"><use href="#inspection"></use></svg>', // 质检系统
                    'gerenshezhi-01': '<svg class="iconpark-icon icon-20"><use href="#building-one"></use></svg>', // 企业中心
                    'pingjiaguanlihuaban1': '<svg class="iconpark-icon icon-20"><use href="#comment-9lc9ep17"></use></svg>', // 评价管理
                    'gongdanxitong-01': '<svg class="iconpark-icon icon-20"><use href="#transaction"></use></svg>' // 工单系统
                }[tree[i].data.resIcon] || tree[i].data.resIcon;
            } else {
                tree[i].data.resIcon = '';
            }
            const key = tree[i].data.resUrl as keysType;
            if (key in replaceUrl) {
                tree[i].data.resUrl = replaceUrl[key];
            }
            handleTree(tree[i].children || []);
        }
        return tree;
    }

    function setTreeData (tree: TreeItemType[]) {
        menuList.value = tree;
    };

    return {
        triggerMenu,
        setShow,
        setTreeData,
        getMenuList,
        menuList,
        isShow
    }
})